package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.model.User;
import com.conversationboard.site.Site;

@WebServlet(name = "AdminRegistrationStatusControllerServlet", urlPatterns = "/Admin/AdminRegistrationStatusControllerServlet")
public class AdminRegistrationStatusControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -7665342670852410972L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {
			Principal principal = request.getUserPrincipal();
			String loginId = "";

			if (!Configuration.getInstance().isAllowBlockRegistration()) {
				return;
			}

			if (principal != null) {
				loginId = principal.getName();
			}

			User user = User.get(loginId);

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			if (user.isSiteAdmin()) {
				boolean registrationAllowed = Site.isRegistrationAllowed();
				Site.allowRegistrations(!registrationAllowed);
			} else {
				request.setAttribute("message", "You are not authorised to perform that action");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/index.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
